package com.m3839.sdk.login.js;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.m3839.sdk.common.base.BaseJsInterface;
import com.m3839.sdk.common.base.UIStackManager;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.ErrorConstant;
import com.m3839.sdk.common.util.LogUtils;
import com.m3839.sdk.login.core.LoginManager;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author ChenBaoyang
 * @description: LoginJsInterface
 * @date 2021/11/15 15:46
 */
public class HykbLoginJsInterface extends BaseJsInterface {

    private static final String KEY_USER_ID = "userId";
    private static final String KEY_NICK = "nick";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_LOGIN_TYPE = "loginType";

    public HykbLoginJsInterface(Context context) {
        super(context);
    }

    /**
     * h5登录结果回调
     *
     * @param json
     */
    @JavascriptInterface
    public void onLoginCallback(String json, int code, String msg) {
        LogUtils.flog("code= " + code + "json=" + json + "====msg==" + msg);
        loginCallBack(json, code, msg);
    }

    private void loginCallBack(String json, int code, String msg) {
        if (code == Constant.HYKB_CODE_LOGIN_SUCCESS) {
            if (!TextUtils.isEmpty(json)) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String userId = jsonObject.getString(KEY_USER_ID);
                    String nick = jsonObject.getString(KEY_NICK);
                    String token = jsonObject.getString(KEY_TOKEN);
                    String loginType = jsonObject.getString(KEY_LOGIN_TYPE);
                    UIStackManager.getInstance().finishFragment(Constant.HYKB_TAG_FRAGMENT_LOGIN_WEB);
                    LoginManager.getInstance().createUser(userId, nick, loginType, token);
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }
        } else {
            LoginManager.getInstance().handleErrorCallback(code, msg);
        }
    }

    @JavascriptInterface
    public void onLoginClose() {
        LogUtils.flog("onLoginClose");
        UIStackManager.getInstance().finishFragment(Constant.HYKB_TAG_FRAGMENT_LOGIN_WEB);
        LoginManager.getInstance().handleErrorCallback(ErrorConstant.HYKB_CODE_LOGIN_CANCEL,
                ErrorConstant.ERR_MSG_SDK_LOGIN_CANCEL);
    }
}
